import './index.js';
console.log('running develop background....');

const reloader = {
	active: false
};

const setupReloadWorker = () => {
	const reloaderConfig = {
		periodInMinutes: 0.01
	};
	
	chrome.alarms.create('background-reloader', reloaderConfig);

	chrome.alarms.onAlarm.addListener((alarm) => {
		if(!reloader.active){
			setupWsConnect();
		}
	
	});

};

const checkReloadInfo = async () => {
	chrome.storage.local.get('reloadInfo', (data) => {
		let reloadInfo = null == data ? {} : data.reloadInfo;
		if(!reloadInfo || !reloadInfo.active ){
			return;
		}
		chrome.tabs.query({active: true}, (tabs) => {
			console.log('reload tabs ....');
			tabs.forEach(tab => chrome.tabs.reload(tab.id, {bypassCache: true}, () => {}));
			chrome.storage.local.set({"reloadInfo": {active: false}}, () => {});

		});

	});


};

const reloadExtApp = () => {
	console.log('reload chrome extension....');
	chrome.storage.local.set({"reloadInfo": {active: true}}, () => {});
	chrome.runtime.reload();
	console.log('chrome reload finish.....');

};

const WS_CONNECTING = 0;
const WS_OPENED = 1;
const WS_CLOSEING = 2;
const WS_CLOSED = 3;
const setupWsConnect = async () => {
	
	checkReloadInfo();

	let readyState = null == reloader.wsConn ? WS_CLOSED : reloader.wsConn.readyState;
	
	if(WS_CONNECTING == readyState){
		console.log('websocket connection is connecting....');
		return;
	}

	if(WS_OPENED == readyState){
		return;
	}

	reloader.wsConn = new WebSocket('ws://localhost:8081/ws');

	reloader.wsConn.addEventListener('open', () => {
		reloader.active = true;
		console.log('websocket connection established...');
		setTimeout(() => reloader.wsConn.send('hello from background ...'), 1000);

	});

	reloader.wsConn.addEventListener('close', () => {
		console.log('websocket connection closed');
		reloader.active = false;

	});

	reloader.wsConn.addEventListener('message', (message) => {
		console.log('receive websocket message', message);
		if('reload' == message.data){
			reloadExtApp();
		}

	});

};

setupReloadWorker();